let express = require('express');
let router = express.Router();
let fs = require('fs')
let path = require('path')
let mgdb = require('../../utils/mgdb')


//2 路由处理响应--增加
router.get('/', (req, res, next) => {
    // console.log('banner')
    //前端增加的banner的数据,集合名,查询的板块,id,页数,跳过几页,全局搜索

    //整理所有的数据
    let { title, sub_title, auth, content } = req.body
    let time = Date.now();
    // let icon, banner;
    let icon = ''
    let banner = ''

    req.files && req.files.forEach((file, index) => {
        //抓取对应的图片
        if (file.fieldname === "icon") {
            icon = '/upload/user/' + file.filename + path.parse(file.originalname).ext;
        }
        if (file.fieldname === 'banner') {
            banner = '/upload/banner/' + file.filename + path.parse(file.originalname).ext;
        }
        fs.renameSync(
            file.path,
            file.path + path.parse(file.originalname).ext
        )
    })

    content = content ? content : '随便写点什么东西'
    banner = banner ? banner : '/upload/user/default.png';
    icon = icon ? icon : '/upload/user/default.png';


    mgdb.open({ collectionName: 'banner' }).then(

        ({ collection, client }) => {
            let data = { title, sub_title, banner, time, detail: { auth_icon: icon, auth, content } }
            collection.insertOne(data, (err, result) => {
                if (!err && result.result.n > 0) {
                    res.send({
                        err: 0,
                        msg: '添加数据成功',
                        data: {
                            _id: result.insertedId,
                            ...data
                        }
                    })
                } else {
                    res.send({ err: 1, msg: '添加到库失败' })
                }
                client.close()
            })
        }
    )

});

router.delete('/:_id', (req, res, next) => {
    // console.log('删除');
    //根据请求头上的id/title//auth来删除
    let _id = req.params._id
        // console.log(_id);
    if (!_id) {
        res.send({ err: 1, msg: '_id为必穿参数' })
        return
    }
    mgdb.open({
        collectionName: 'banner'
    }).then(
        ({ collection, client, ObjectId }) => {
            console.log(ObjectId(_id))
                // deleteOne({条件},(err,result)=>{})
            collection.deleteOne({
                _id: ObjectId(_id)
            }, (err, result) => {
                if (result.result.n > 0) {
                    res.send({ err: 0, msg: '删除成功' })
                } else {
                    res.send({ err: 1, msg: '删除失败' })
                }
                client.close()
            })

        }
    )
});


//修改
router.patch('/:_id', (req, res, next) => {
    let _id = req.params._id;
    if (!_id) {
        res.send({ err: 1, msg: '_id为必传参数' })
        return;
    }

    //查询
    mgdb.open({
        collectionName: 'banner'
    }).then(
        ({ collection, client, ObjectId }) => {
            collection.find({
                _id: ObjectId(_id)
            }).toArray((err, result) => {

                console.log(1, result)

                //准备修改后的数据
                let { title, sub_title, auth, content } = req.body
                title = title || result[0].title
                sub_title = sub_title || result[0].sub_title
                auth = auth || result[0].detail.auth
                content = content || result[0].detail.content

                let auth_icon, banner;

                req.files && req.files.forEach((file, index) => {
                    if (file.fieldname === "icon") {
                        auth_icon = '/upload/user/' + file.filename + path.parse(file.originalname).ext;
                    }
                    if (file.fieldname === 'banner') {
                        banner = '/upload/banner/' + file.filename + path.parse(file.originalname).ext;
                    }

                    fs.renameSync(
                        file.path,
                        file.path + path.parse(file.originalname).ext
                    )

                })

                auth_icon = auth_icon || result[0].detail.auth_icon
                banner = banner || result[0].banner

                let time = Date.now()

                //修改
                collection.updateMany({
                    _id: ObjectId(_id)
                }, {
                    $set: {
                        title,
                        sub_title,
                        banner,
                        time,
                        detail: { auth_icon, auth, content }
                    }
                }, {
                    upsert: false,
                    projection: false
                }, (err, result) => {
                    if (result.result.n > 0) {
                        res.send({ err: 0, msg: '修改成功' })
                    } else {
                        res.send({ err: 1, msg: '修改失败' })
                    }
                    client.close()
                })
            })
        }
    )




})

//3. 导出路由
module.exports = router;